/**
 * Created by apple on 16/5/24.
 */
class Controller {
    constructor(ApiService, $scope, $state, $cookies, $rootScope) {
        "ngInject"

        this.rootScope = $rootScope;
        this.state     = "";

        ApiService.getMenuUser({
            sysCode: 'ctg-ae'
        }).then((res) => {
            this.menus = res.data.menus;
            this.addPlusUrl(this.menus);
            $rootScope.isMenuLoad = true;
            // angular.element('#mainFrame').attr("src", "http://orderportal.ctg.com:8011/notexistedRequest");
        })

        $scope.$watch(() => {
            return $state.current.url
        }, () => {
            this.state = $state.current.name;
        })
    }

    makeAction($event) {
        $event.preventDefault();
        let $e = angular.element($event.currentTarget), $ifr = angular.element('#mainFrame');
        this.rootScope.isFrame = true;
        this.rootScope.isFrameLoading = true;
        /**
         * href替换模板 例如：
         * 替换前：http://orderportal.ctg.com:8011/console/dist/index.html#/sale-service/report/business-inventory?display=0
         * 替换后：http://orderportal.ctg.com:8011/route?mainPage=/console/dist/index.html&route=/sale-service/report/business-inventory?display=0
         */
        let href = $e.attr('href');
        href = href.split("#")[0].replace(/console/, "route?mainPage=/console") + "&route=" + href.split("#")[1];
        $ifr.attr('src', href).on('load', () => {
            $ifr.prev().remove()
        });
    }

    toggleOpenMenu(menu) {
        menu.fold = !menu.fold
    }

    calcMenuHeight(menu) {
        return {
            height: 40 * menu.item.length
        }
    }

    addPlusUrl(menus) {

        let host = window.location.host;
        console.log("当前Host: " + host);

        if (host.indexOf("plus") >= 0) {
            for (var i = 0; i < menus.length; i++) {
                if (menus[i]['item'] == null) continue;
                for (var j = 0; j < menus[i]['item'].length; j++) {
                    if (menus[i]['item'][j]["url_addr"] == null 
                        || menus[i]['item'][j]["url_addr"].indexOf("orderportal") < 0)
                        continue;
                    menus[i]['item'][j]["url_addr"] = menus[i]['item'][j]["url_addr"].replace("orderportal.ctg.com","orderportalplus.ctg.com");
                }
            }
        }
    }
}

export default Controller;
